package com.pocketsweet.ui;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceActivity.Header;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.RefreshCallback;
import com.avos.avoscloud.SaveCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLConsumeRecord;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.pay.alipay.Result;
import com.pocketsweet.pay.alipay.SignUtils;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_wallet)
public class MyWallet extends BaseActivity implements View.OnClickListener {

	@ViewInject(R.id.mainHeader)
	private static HeaderLayout header;

	@ViewInject(R.id.tvRecharge)
	private static TextView tvRecharge;

	@ViewInject(R.id.tvMyMoney)
	private static TextView tvMyMoney;

	@ViewInject(R.id.tvWithdraw)
	private static TextView tvWithdraw;

	@ViewInject(R.id.imgTaskPic)
	private static ImageView imgTaskPic;

	@ViewInject(R.id.linRecharge)
	private static LinearLayout linRecharge;

	@ViewInject(R.id.relWallet)
	private static RelativeLayout relWallet;

	@ViewInject(R.id.relRecharge50)
	private static RelativeLayout relRecharge50;

	@ViewInject(R.id.relRecharge200)
	private static RelativeLayout relRecharge200;

	@ViewInject(R.id.relRecharge320)
	private static RelativeLayout relRecharge320;

	@ViewInject(R.id.relRecharge660)
	private static RelativeLayout relRecharge660;

	@ViewInject(R.id.relRecharge1180)
	private static RelativeLayout relRecharge1180;

	@ViewInject(R.id.relRecharge5880)
	private static RelativeLayout relRecharge5880;

	private double balance;
	private double peroid;
	private LoadingDailog loading;
	private int chargerNum = 5;
	private MLUser curUser;

	private static final int SDK_PAY_FLAG = 1;

	private static final int SDK_CHECK_FLAG = 2;

	private PackageManager manager;
	private PackageInfo info = null;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				Result resultObj = new Result((String) msg.obj);
				String resultStatus = resultObj.resultStatus;

				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Main.isBalanceChange = true;
					Toast.makeText(MyWallet.this, "支付成功", Toast.LENGTH_SHORT)
							.show();
					// 修改后台数据
					curUser.increment("balance", chargerNum);
					curUser.saveInBackground(new SaveCallback() {

						@Override
						public void done(AVException arg0) {
							// 增加消费记录
							MLConsumeRecord consum = new MLConsumeRecord();
							consum.setMoney(chargerNum);
							consum.setType(C.CONSUME_TYPE_RECHARGE);
							consum.setRemark("充值" + chargerNum + "元");
							consum.setSn(ToolKits.generateOrderCode());
							consum.setDevice(C.USER_DEVICE_ANDROID);
							consum.setSysInfo(android.os.Build.MODEL + " - "
									+ android.os.Build.VERSION.RELEASE);
							consum.setuser(curUser);
							manager = MyWallet.this.getPackageManager();
							try {
								info = manager.getPackageInfo(MyWallet.this.getPackageName(), 0);
								consum.setVersion(info.versionName.toString());
							} catch (PackageManager.NameNotFoundException e) {

								// TODO Auto-generated catch block

								e.printStackTrace();
							}
							consum.saveInBackground();
						}
					});
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”
					// 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(MyWallet.this, "支付结果确认中",
								Toast.LENGTH_SHORT).show();

					} else {
						Toast.makeText(MyWallet.this, "支付失败",
								Toast.LENGTH_SHORT).show();

					}
				}
				break;
			}
			case SDK_CHECK_FLAG: {
				Toast.makeText(MyWallet.this, "检查结果为：" + msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		curUser = UserService.getCurrentUser();
		initListener();
		initView();
		initHead();
	}

	private void initView() {
		linRecharge.setVisibility(View.GONE);
		imgTaskPic.setVisibility(View.GONE);
		tvWithdraw.setVisibility(View.VISIBLE);
		tvRecharge.setVisibility(View.VISIBLE);
	}

	private void initHead() {
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setMiddleText("钱包");
		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				MyWallet.this.finish();
			}
		});
		if (UserService.getCurrentUser().getType() != C.USER_TYPE_NORMAL) {
			header.setRightText("");
			return;
		}
		header.setRightText("充值记录");
		header.setRighttContainerClickListener(new onRightContainerListener() {

			@Override
			public void onClick() {
				// 跳到充值记录
				Intent intent = new Intent(MyWallet.this, RechargeRecord.class);
				MyWallet.this.startActivity(intent);
			}
		});

	}

	private void initListener() {
		relRecharge50.setOnClickListener(this);
		relRecharge200.setOnClickListener(this);
		relRecharge320.setOnClickListener(this);
		relRecharge660.setOnClickListener(this);
		relRecharge1180.setOnClickListener(this);
		relRecharge5880.setOnClickListener(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		loading = ToolKits.createLoadingDialog(MyWallet.this, "提交中..");
		loading.setText("加载中");
		loading.show();
		UserService.getCurrentUser().refreshInBackground(
				new RefreshCallback<AVObject>() {

					@Override
					public void done(AVObject arg0, AVException arg1) {
						loading.dismiss();
						balance = UserService.getCurrentUser().getBalance();
						peroid = balance * 10;
						if (peroid == 0) {
							tvMyMoney.setText("0时光");
						} else {
							tvMyMoney.setText((int) peroid + "时光");
							// tvMyMoney.setText(new
							// BigDecimal(peroid).setScale(
							// 2, BigDecimal.ROUND_HALF_UP) + "时光");
						}
						MLUser user = UserService.getCurrentUser();
						if (user.getType() == C.USER_TYPE_NORMAL) {
							relWallet.setVisibility(View.VISIBLE);
							linRecharge.setVisibility(View.VISIBLE);
							imgTaskPic.setVisibility(View.VISIBLE);
							tvWithdraw.setVisibility(View.GONE);
						} else {
							relWallet.setVisibility(View.VISIBLE);
							linRecharge.setVisibility(View.GONE);
							imgTaskPic.setVisibility(View.GONE);
							tvRecharge.setVisibility(View.VISIBLE);
							tvWithdraw.setVisibility(View.VISIBLE);
						}
					}
				});
		// balance = getIntent().getDoubleExtra("balance", 0);
	}

	public void back(View v) {
		MyWallet.this.finish();
	}

	@OnClick(R.id.tvRecharge)
	public void onRechargerClick(View v) {
		Intent intent = new Intent(this, Wallet.class);
		this.startActivity(intent);
	}

	@OnClick(R.id.tvWithdraw)
	public void onWithdrawClick(View v) {
		AVAnalytics.onEvent(this, "提现");
		Intent intent = new Intent(this, Withdraw.class);
		intent.putExtra("balance", balance);
		this.startActivity(intent);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.relRecharge50:
			chargerNum = 1;
			onRecharge();
			break;
		case R.id.relRecharge200:
			chargerNum = 20;
			onRecharge();
			break;
		case R.id.relRecharge320:
			chargerNum = 40;
			onRecharge();
			break;
		case R.id.relRecharge660:
			chargerNum = 60;
			onRecharge();
			break;
		case R.id.relRecharge1180:
			chargerNum = 120;
			onRecharge();
			break;
		case R.id.relRecharge5880:
			chargerNum = 600;
			onRecharge();
			break;

		}
	}

	public void onRecharge() {
		// 充值
		String orderInfo = getOrderInfo("袋币充值", chargerNum + "元", chargerNum
				+ "");
		String sign = sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(MyWallet.this);
				// 调用支付接口
				String result = alipay.pay(payInfo);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	public String getOrderInfo(String subject, String body, String price) {
		// 合作者身份ID
		String orderInfo = "partner=" + "\"" + C.PARTNER + "\"";

		// 卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + C.SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + "http://notify.msp.hk/notify.htm"
				+ "\"";

		// 接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 获取外部订单号
	 * 
	 */
	public String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	public String sign(String content) {
		return SignUtils.sign(content, C.RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public String getSignType() {
		return "sign_type=\"RSA\"";
	}

	/**
	 * check whether the device has authentication alipay account.
	 * 查询终端设备是否存在支付宝认证账户
	 * 
	 */
	public void check(View v) {
		Runnable checkRunnable = new Runnable() {

			@Override
			public void run() {
				PayTask payTask = new PayTask(MyWallet.this);
				boolean isExist = payTask.checkAccountIfExist();

				Message msg = new Message();
				msg.what = SDK_CHECK_FLAG;
				msg.obj = isExist;
				mHandler.sendMessage(msg);
			}
		};

		Thread checkThread = new Thread(checkRunnable);
		checkThread.start();

	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}
}
